import XunfeiSpark from './xunfeiSpark'

let sparkInstance: XunfeiSpark | null = null
const cache = new Map<string, string>()

function getSpark(): XunfeiSpark | null {
  try {
    if (sparkInstance) return sparkInstance
    const appId = import.meta.env.VITE_XUNFEI_APP_ID || ''
    const apiKey = import.meta.env.VITE_XUNFEI_API_KEY || ''
    const apiSecret = import.meta.env.VITE_XUNFEI_API_SECRET || ''
    if (!appId || !apiKey || !apiSecret) {
      console.warn('autoTranslate: 环境变量未配置，跳过调用星火翻译。')
      return null
    }
    sparkInstance = new XunfeiSpark({ appId, apiKey, apiSecret, domain: 'generalv3.5' })
    return sparkInstance
  } catch (e) {
    console.error('初始化星火服务失败:', e)
    return null
  }
}

function detectContainsChinese(text: string): boolean {
  return /[\u4e00-\u9fa5]/.test(text)
}

function detectContainsLatin(text: string): boolean {
  return /[A-Za-z]/.test(text)
}

export async function translateText(text: string, targetLang: 'zh' | 'en'): Promise<string> {
  const key = `${targetLang}::${text}`
  if (cache.has(key)) return cache.get(key) as string

  // 简单语言判断与短路
  const hasZh = detectContainsChinese(text)
  const hasEn = detectContainsLatin(text)
  if ((targetLang === 'zh' && hasZh && !hasEn) || (targetLang === 'en' && hasEn && !hasZh)) {
    cache.set(key, text)
    return text
  }

  const spark = getSpark()
  if (!spark) {
    // 无模型配置时直接返回原文
    return text
  }

  const systemPrompt = targetLang === 'en'
    ? 'You are a professional translator. Translate the user content into natural English. Only return the translation, no explanation.'
    : '你是专业的翻译助手。请把用户内容翻译成自然的中文。只返回翻译结果，不要解释。'

  try {
    const result = await spark.sendMessage(text, systemPrompt)
    const trimmed = String(result).trim()
    // 防止返回空/无效
    const output = trimmed.length ? trimmed : text
    cache.set(key, output)
    return output
  } catch (e) {
    console.error('调用星火翻译失败，回退原文:', e)
    return text
  }
}